﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace QuanLyPhongKham
{
    public partial class ucDonThuoc : BaseUserControl
    {
        private DAL.AccessData m = new DAL.AccessData();
        private DataSet ds = new DataSet();
        private string s_mabn, s_hoten, s_namsinh, s_ngay, s_bacsi, s_chandoan, s_makp, s_mabs, s_ngaycapdon = "", s_mmyy = "";
        private long l_maql, l_id = 0, l_maql_old = 0;
        private decimal d_soluong = 0, d_soluongcu = 0;
        private int i_userid, i_songay = 1, i_mabd = 0, i_stt = 0, i_sophieu = 0, i_makho, i_manguon;
        private DataTable dtmabd=new DataTable();
        private DataTable dtcachdung = new DataTable();
        private DataTable dtct = new DataTable();
        private DataTable dtxoa = new DataTable();
        private DataTable dtthem = new DataTable();
        private DataTable dtsua = new DataTable();
        private DataTable dtsave = new DataTable();
        private DataTable dtdiung = new DataTable();
        private bool bNew = false, bEdit = false;
        public ucDonThuoc(long maql,string mabn,string hoten,string namsinh,string ngay,string bacsi,string chandoan,string mabs,string makp,int userid,string mmyy)
        {
            InitializeComponent();
            l_maql = maql;
            s_mabn = mabn; s_hoten = hoten;
            s_namsinh = namsinh; s_ngay = ngay;
            s_bacsi = bacsi; s_chandoan = chandoan;
            s_mabs = mabs; s_makp = makp; i_userid = userid; s_mmyy = mmyy;
        }

        private void frmDonthuoc_SizeChanged(object sender, EventArgs e)
        {
            bNut.Location = new Point((this.Width - 628) / 2 + 1, 301 + this.Height - 470);
            gDonthuoc.Location = new Point((this.Width - 628) + 481, 0);
            gDonthuoc.Size = new Size(gDonthuoc.Width, 294 + (this.Height - 470));
            groupBox2.Location = new Point((this.Width - 628) + 482, 0);
            groupBox2.Size = new Size(groupBox2.Width, 294 + (this.Height - 470));
            dataGrid1.Size = new Size(dataGrid1.Width, 207 + (this.Height - 470));
            mathuoc.Location = new Point(63, 227 + this.Height - 470);
            tenthuoc.Location = new Point(175, 227 + this.Height - 470);
            hoatchat.Location = new Point(63, 250 + this.Height - 470);
            dvt.Location = new Point(63, 273 + this.Height - 470);
            soluong.Location = new Point(175, 273 + this.Height - 470);
            cachdung.Location = new Point(281, 273 + this.Height - 470);
            lMathuoc.Location = new Point(8, 232 + this.Height - 470);
            lTenthuoc.Location = new Point(117, 232 + this.Height - 470);
            lHoatchat.Location = new Point(5, 255 + this.Height - 470);
            lDvt.Location = new Point(0, 278 + this.Height - 470);
            lSoluong.Location = new Point(123, 278 + this.Height - 470);
            lCachdung.Location = new Point(220, 278 + this.Height - 470);
        }

        private void butKetthuc_Click(object sender, EventArgs e)
        {
            //fix:
            //this.Close();
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Action == TreeViewAction.ByMouse || e.Action == TreeViewAction.ByKeyboard)
            {
                try
                {
                    s_ngaycapdon = e.Node.FullPath;
                    l_id = long.Parse(e.Node.Tag.ToString());
                    if (l_id != 0)
                    {
                        DataRow r = m.getrowbyid(ds.Tables[0], "id=" + l_id);
                        if (r != null)
                        {
                            l_maql_old = long.Parse(r["maql"].ToString());
                            i_sophieu = int.Parse(r["sophieu"].ToString());
                            ghichu.Text=r["ghichu"].ToString();
                        }
                        load_grid();
                        ref_text();
                        ena_button(true);
                        ena_object(false);
                    }
                }
                catch { }
            }
        }

        private void mabn_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SendKeys.Send("{Tab}");
            }
        }
        private void MaskDigit(KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar) || e.KeyChar == 8 || e.KeyChar == '.') e.Handled = false;
            else e.Handled = true;
        }

        private void mabn_KeyPress(object sender, KeyPressEventArgs e)
        {
            MaskDigit(e);
        }

        private void ghichu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SendKeys.Send("{Tab}");
            }
        }

        private void frmDonthuoc_Load(object sender, EventArgs e)
        {
            load_danhmuc();
            load_thongtinbn();
            load_sudungthuoc();
            load_diungthuoc();
            load_grid();
            AddGridTableStyle();
            ref_text();
            ena_object(false);
            ena_button(true);
        }
        private void load_diungthuoc()
        {
            dtdiung = m.get_data("select mahc from " + m.user + ".d_diungthuoc where mabn='" + mabn.Text + "'").Tables[0];
        }
        private void load_sudungthuoc()
        {
            treeView1.Nodes.Clear();
            ds = m.get_data("select a.id,a.sophieu,a.maql,a.ghichu,to_char(a.ngay,'dd/mm/yyyy') as ngay,to_char(ngay,'yyyymmdd') as sort,b.stt,b.mabd,c.ma,trim(c.ten||' '||c.hamluong) as ten,c.dang,b.soluong from " + m.user + ".d_donthuocll_"+s_mmyy+" a,"+m.user+".d_donthuocct_"+s_mmyy+" b,"+m.user+".d_dmbd c where a.id=b.id and b.mabd=c.id and a.mabn='" + mabn.Text + "' order by sort desc,id,stt asc");
            TreeNode node=new TreeNode();
            TreeNode node_con;
            string s_node = "";
            bool be = false;
            foreach (DataRow r in ds.Tables[0].Rows)
            {
                be = false;
                if (s_node != r["id"].ToString())
                {
                    node = new TreeNode(r["ngay"].ToString());
                    if (l_maql == long.Parse(r["maql"].ToString()))
                    {
                        l_maql_old = long.Parse(r["maql"].ToString());
                        l_id = long.Parse(r["id"].ToString());
                        s_ngaycapdon = r["ngay"].ToString();
                    }
                    s_node = r["id"].ToString();
                    node.Tag = r["id"].ToString();
                    be = true;
                }
                node_con = new TreeNode(r["ten"].ToString()+" / "+r["dang"].ToString()+" ("+decimal.Parse(r["soluong"].ToString())+")");
                node.Nodes.Add(node_con);
                if (be)
                {
                    treeView1.Nodes.Add(node);
                }
            }
        }
        private void load_grid()
        {
            dtct = m.get_data("select a.id, a.stt, a.mabd, b.ma, trim(b.ten||' '||b.hamluong) as ten, b.tenhc, b.dang, a.soluong, a.cachdung, a.makho, a.manguon from " + m.user + ".d_donthuocct_"+s_mmyy+" a,"+m.user+".d_dmbd b where a.mabd=b.id and a.id=" + l_id + " order by a.stt").Tables[0];
            dataGrid1.DataSource = dtct;
            dtxoa = dtct.Clone();
            dtthem = dtct.Clone();
        }
        private void AddGridTableStyle()
        {
            DataGridColoredTextBoxColumn TextCol;
            delegateGetColorRowCol de = new delegateGetColorRowCol(MyGetColorRowCol);
            DataGridTableStyle ts = new DataGridTableStyle();
            ts.MappingName = dtct.TableName;
            ts.AlternatingBackColor = Color.Linen;
            ts.BackColor = Color.GhostWhite;
            ts.ForeColor = Color.MidnightBlue;
            ts.GridLineColor = SystemColors.Control;
            ts.HeaderBackColor = SystemColors.Control;
            ts.HeaderForeColor = Color.Navy;
            ts.SelectionBackColor = Color.Teal;
            ts.SelectionForeColor = Color.White;
            ts.ReadOnly = true;
            ts.RowHeaderWidth = 5;

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "id";
            TextCol.HeaderText = "id";
            TextCol.Width = 0;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 1);
            TextCol.MappingName = "stt";
            TextCol.HeaderText = "STT";
            TextCol.Width = 50;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 2);
            TextCol.MappingName = "mabd";
            TextCol.HeaderText = "Mã thuốc";
            TextCol.Width = 0;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 3);
            TextCol.MappingName = "ma";
            TextCol.HeaderText = "Mã";
            TextCol.Width = 60;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 4);
            TextCol.MappingName = "ten";
            TextCol.HeaderText = "Tên thuốc - hàm lượng";
            TextCol.Width = 300;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 5);
            TextCol.MappingName = "tenhc";
            TextCol.HeaderText = "Hoạt chất";
            TextCol.Width = 120;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 6);
            TextCol.MappingName = "soluong";
            TextCol.HeaderText = "Số lượng";
            TextCol.Width = 80;
            TextCol.Format = "###,###,###,##0";
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 7);
            TextCol.MappingName = "dang";
            TextCol.HeaderText = "ĐVT";
            TextCol.Width = 70;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 8);
            TextCol.MappingName = "cachdung";
            TextCol.HeaderText = "Cách dùng";
            TextCol.Width = 250;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 9);
            TextCol.MappingName = "makho";
            TextCol.HeaderText = "";
            TextCol.Width = 0;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 10);
            TextCol.MappingName = "manguon";
            TextCol.HeaderText = "";
            TextCol.Width = 0;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);
        }
        public Color MyGetColorRowCol(int row, int col)
        {
            Color c = Color.Navy;
            try
            {
                if (row == dataGrid1.CurrentRowIndex)
                {
                    dataGrid1.Select(row);
                    c = Color.White;
                }
            }
            catch
            {
            }
            return c;
        }
        public delegate Color delegateGetColorRowCol(int row, int col);
        public class DataGridColoredTextBoxColumn : DataGridTextBoxColumn
        {
            private delegateGetColorRowCol _getColorRowCol;
            private int _column;
            public DataGridColoredTextBoxColumn(delegateGetColorRowCol getcolorRowCol, int column)
            {
                _getColorRowCol = getcolorRowCol;
                _column = column;
            }
            protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight)
            {
                try
                {
                    foreBrush = new SolidBrush(_getColorRowCol(rowNum, this._column));
                }
                catch { }
                finally
                {
                    base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);
                }
            }
        }
        private void load_thongtinbn()
        {
            mabn.Text = s_mabn; hoten.Text = s_hoten; namsinh.Text = s_namsinh;
            ngaykham.Text = s_ngay; bacsi.Text = s_bacsi; chandoan.Text = s_chandoan;
        }
        private void load_danhmuc()
        {
            listcachdung.DisplayMember = "ID";
            listcachdung.ValueMember = "TEN";
            listthuoc.DisplayMember = "ID";
            listthuoc.ValueMember = "TEN";
            //dtmabd = m.get_data("select * from "+m.user+".d_dmbd where hide=0 order by ten").Tables[0];
            dtmabd = m.get_tonkhoth(s_mmyy, "", "");
            listthuoc.DataSource = dtmabd;
            load_cachdung();
        }
        private void load_cachdung()
        {
            try
            {
                dtcachdung=m.get_data("select id,ten from " + m.user + ".d_dmcachdung order by ten").Tables[0];
                listcachdung.DataSource = dtcachdung;
            }
            catch { macachdung.Text = ""; }
        }
        private void cachdung_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up) listcachdung.Focus();
            else if (e.KeyCode == Keys.Enter)
            {
                if (listcachdung.Visible) listcachdung.Focus();
                else butThem.Focus();
            }
        }
        private void ena_button(bool ena)
        {
            butMoi.Enabled = ena;
            butLuu.Enabled = !ena;
            butThem.Enabled = !ena;
            butXoa.Enabled = !ena;
            butSua.Enabled = ena;
            butHuy.Enabled = ena;
            butBoqua.Enabled = !ena;
            butIn.Enabled = ena;
            butKetthuc.Enabled = ena;
        }
        private void butMoi_Click(object sender, EventArgs e)
        {
            if (kiemtra_sudung())
            {
                ena_button(true); ena_object(false);
                return;
            }
            bNew = true; bEdit = false; i_stt = 0; i_makho = 0; i_manguon = 0;
            dtct.Clear();
            dtsave.Clear();
            dtxoa.Clear();
            dtthem.Clear();
            emp_detail();
            ena_button(false); ena_object(true);
            ghichu.Focus();
        }
        private void butLuu_Click(object sender, EventArgs e)
        {
            upd_table();
            if (dtct.Rows.Count <= 0 && !bEdit) return;
            l_id = (bNew) ? m.get_capid : l_id;
            i_sophieu = (bNew) ? m.get_sophieu(m.ngayhienhanh_server.Substring(0, 10)) : i_sophieu;
            if (!m.upd_donthuocll(s_mmyy,l_id, i_sophieu, mabn.Text, l_maql, m.ngayhienhanh_server, s_makp, chandoan.Text, "", s_mabs, ghichu.Text, i_userid, i_songay))
            {
                MessageBox.Show("Không cập nhật được thông tin đơn thuốc!");
                return;
            }
            if (bEdit && !bNew)
            {
                foreach (DataRow r in dtxoa.Rows)
                {
                    m.execute_data("delete from " + m.user + ".d_donthuocct_"+s_mmyy+" where id=" + l_id + " and stt=" + int.Parse(r["stt"].ToString()));
                    m.upd_theodoisua(m.get_capid_theodoisua, mabn.Text, l_maql, int.Parse(r["mabd"].ToString()), r["ten"].ToString(), decimal.Parse(r["soluong"].ToString()), i_userid, "BN", "d_donthuocct_"+s_mmyy+"", 0, 0, 1);
                }
                foreach (DataRow r in dtthem.Rows)
                    m.upd_theodoisua(m.get_capid_theodoisua, mabn.Text, l_maql, int.Parse(r["mabd"].ToString()), r["ten"].ToString(), decimal.Parse(r["soluong"].ToString()), i_userid, "BN", "d_donthuocct_"+s_mmyy+"", 1, 0, 0);
                foreach (DataRow r in dtct.Rows)
                {
                    DataRow nr = m.getrowbyid(dtsave, "mabd=" + int.Parse(r["mabd"].ToString()) + " and stt=" + int.Parse(r["stt"].ToString()));
                    if (nr != null)
                    {
                        decimal d_soluongcu = decimal.Parse(nr["soluong"].ToString());
                        if (d_soluongcu != decimal.Parse(r["soluong"].ToString()))
                            m.upd_theodoisua(m.get_capid_theodoisua, mabn.Text, l_maql, int.Parse(r["mabd"].ToString()), r["ten"].ToString(), d_soluongcu, i_userid, "BN", "d_donthuocct_"+s_mmyy+"", 0, 1, 0);
                    }
                }
            }
            foreach (DataRow r in dtct.Rows)
                m.upd_donthuocct(s_mmyy, true, l_id, int.Parse(r["stt"].ToString()), int.Parse(r["mabd"].ToString()), decimal.Parse(r["soluong"].ToString()), r["cachdung"].ToString(), i_makho, i_manguon);
            if (dtct.Rows.Count == 0) m.execute_data("delete from " + m.user + ".d_donthuocll_"+s_mmyy+" where id=" + l_id);
            if (bNew) s_ngaycapdon = m.ngayhienhanh_server;
            bNew = false; bEdit = false;
            ena_object(false);
            load_grid();
            load_sudungthuoc();
            ref_text();
            ena_button(true);
        }
        private bool kiemtra_sudung()
        {
            foreach (DataRow r in m.get_data("select id,to_char(ngay,'dd/mm/yyyy') as ngay from " + m.user + ".d_donthuocll_"+s_mmyy+" where to_char(ngay,'dd/mm/yyyy')='" + m.ngayhienhanh_server + "' and mabn='" + mabn.Text + "' and maql=" + l_maql).Tables[0].Rows)
            {
                MessageBox.Show("Trong ngày người bệnh đã được cấp đơn thuốc !", DAL.AccessData.Msg);
                l_id = long.Parse(r["id"].ToString());
                s_ngaycapdon = r["ngay"].ToString();
                load_grid();
                ref_text();
                return true;
            }
            return false;
        }
        private void butThem_Click(object sender, EventArgs e)
        {
            upd_table();
            if (bNew && macachdung.Text == "")
            {
                m.upd_d_cachdung_dvt_quycach(m.get_capid_dmcachdung, cachdung.Text, "d_dmcachdung");
                load_cachdung();
            }
            emp_detail();
            mathuoc.Focus();
            i_stt = 0;
        }
        private void upd_table()
        {
            if (!kiemtra_detail()) return;
            i_stt = (i_stt == 0) ? get_stt() : i_stt;
            m.updrec_donthuocct(dtct, l_id, i_stt, i_mabd, mathuoc.Text, tenthuoc.Text, hoatchat.Text, dvt.Text, d_soluong, cachdung.Text, i_makho, i_manguon, dtmabd);
            if (bEdit && m.getrowbyid(dtct, "mabd=" + i_mabd + " and stt=" + i_stt) != null) m.updrec_donthuocct(dtthem, l_id, i_stt, i_mabd, mathuoc.Text, tenthuoc.Text, hoatchat.Text, dvt.Text, d_soluong, cachdung.Text, i_makho, i_manguon, dtmabd);
            dataGrid1.Refresh();
        }
        private int get_stt()
        {
            int _stt = 0, var = 0;
            try 
            {
                foreach (DataRow r in dtct.Select("true","stt"))
                {
                    _stt = int.Parse(r["stt"].ToString());
                    if ((var + 1) != _stt)
                    {
                        var = var + 1;
                        return var;
                    }
                    else var = _stt;
                }
                var += 1;
            }
            catch { var += 1; }
            return var;
        }
        private bool kiemtra_detail()
        {
            if (mathuoc.Text == "" || tenthuoc.Text == "")
            {
                mathuoc.Focus();
                return false;
            }
            return true;
        }
        private void emp_detail()
        {
            mathuoc.Text = "";
            tenthuoc.Text = "";
            dvt.Text = "";
            soluong.Text = "";
            hoatchat.Text = "";
            cachdung.Text = "";
            macachdung.Text = "";
            d_soluongcu = 0;
        }
        private void butSua_Click(object sender, EventArgs e)
        {
            if (l_id == 0) return;
            if ((s_ngaycapdon != m.ngayhienhanh_server && s_ngaycapdon != "") || l_maql != l_maql_old)
            {
                MessageBox.Show("Đơn này đã cấp vào ngày khác hoặc của đợt điều trị khác, không được chỉnh sửa!", DAL.AccessData.Msg);
                return;
            }
            bEdit = true; bNew = false;
            dtxoa.Clear(); dtthem.Clear();
            dtsave = dtct.Copy();
            ena_button(false);
            ena_object(true);
            ref_text();
            dataGrid1.Focus();
        }
        private void butHuy_Click(object sender, EventArgs e)
        {
            try
            {
                if (dtct.Rows.Count == 0 || l_id == 0) return;
                if (s_ngaycapdon != m.ngayhienhanh_server && s_ngaycapdon != "")
                {
                    MessageBox.Show("Đơn này đã được cấp vào ngày khác, không được huỷ!", DAL.AccessData.Msg); return;
                }
                if (m.get_data("select done from " + m.user + ".d_donthuocll_" + s_mmyy + " where id=" + l_id + " and done=1").Tables[0].Rows.Count > 0)
                {
                    MessageBox.Show("Đơn này đã được bán cho bệnh nhân, không được huỷ!", DAL.AccessData.Msg); return;
                }
                if (MessageBox.Show("Đồng ý hủy đơn thuốc này ?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    m.execute_data("delete from " + m.user + ".d_donthuocct_"+s_mmyy+" where id=" + l_id);
                    m.execute_data("delete from " + m.user + ".d_donthuocll_" + s_mmyy + " where id=" + l_id);
                    m.delrec(dtct, "id=" + l_id);
                    load_sudungthuoc();
                    dataGrid1.Refresh();
                }
            }
            catch
            {
            }
            ena_button(true);
            ena_object(false);
        }
        private void butBoqua_Click(object sender, EventArgs e)
        {
            bNew = false; bEdit = false; 
            ena_button(true);
            ena_object(false);
            load_grid();
            ref_text();
        }
        private void cachdung_TextChanged(object sender, EventArgs e)
        {
            if (this.ActiveControl == cachdung)
            {
                try
                {
                    Filt_cachdung(cachdung.Text);
                    listcachdung.BrowseToBtdkp(cachdung, macachdung, butThem);
                }
                catch { macachdung.Text = ""; }
            }
        }
        private void Filt_cachdung(string ten)
        {
            try
            {
                CurrencyManager cm = (CurrencyManager)BindingContext[listcachdung.DataSource];
                DataView dv = (DataView)cm.List;
                dv.RowFilter = "ten like '%" + ten.Trim() + "%'";
            }
            catch { macachdung.Text = ""; }
        }
        private void tenthuoc_TextChanged(object sender, EventArgs e)
        {
            if (this.ActiveControl == tenthuoc)
            {
                try
                {
                    Filt_tenthuoc(tenthuoc.Text);
                    //listthuoc.BrowseToTonkho(tenthuoc, mathuoc, soluong, mathuoc.Location.X, mathuoc.Location.Y + mathuoc.Height, mathuoc.Width + tenthuoc.Width + lTenthuoc.Width - 4, mathuoc.Height);
                    listthuoc.Tonkhoct(tenthuoc, mathuoc, soluong, mathuoc.Location.X, mathuoc.Location.Y + mathuoc.Height, mathuoc.Width + tenthuoc.Width + lTenthuoc.Width - 4, mathuoc.Height);
                }
                catch { }
            }
        }
        private void Filt_tenthuoc(string ten)
        {
            try
            {
                CurrencyManager cm = (CurrencyManager)BindingContext[listthuoc.DataSource];
                DataView dv = (DataView)cm.List;
                dv.RowFilter = "ten like '%" + ten.Trim() + "%' or tenhc like '%" + ten.Trim() + "%'";
            }
            catch { }
        }
        private void tenthuoc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up) listthuoc.Focus();
            else if (e.KeyCode == Keys.Enter)
            {
                if (listthuoc.Visible) listthuoc.Focus();
                else SendKeys.Send("{Tab}{Home}");
            }
        }
        private void listthuoc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    DataRow r = m.getrowbyid(dtmabd, "stt=" + int.Parse(mathuoc.Text));
                    if (r != null)
                    {
                        string s_mahc = "";
                        i_mabd = int.Parse(r["id"].ToString());
                        mathuoc.Text = r["ma"].ToString();
                        tenthuoc.Text = r["ten"].ToString();
                        hoatchat.Text = r["tenhc"].ToString();
                        s_mahc = r["mahc"].ToString();
                        dvt.Text = r["dang"].ToString();
                        i_makho = int.Parse(r["makho"].ToString());
                        i_manguon = int.Parse(r["manguon"].ToString());
                        DataRow rr = m.getrowbyid(dtdiung, "mahc='" + s_mahc + "'");
                        if (rr!=null)
                        {
                            if (MessageBox.Show("Người bệnh dị ứng hoạt chất thuốc : " + hoatchat.Text.Trim() + "\nBạn có đồng ý thêm vào không !", DAL.AccessData.Msg, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) soluong.Focus();
                            else
                            {
                                mathuoc.Text = ""; tenthuoc.Text = ""; hoatchat.Text = ""; dvt.Text = ""; s_mahc = "";
                                mathuoc.Focus();
                            }
                        }
                    }
                    listthuoc.Hide();
                    soluong.Focus();
                }
                catch { }
            }
        }
        private void soluong_Validated(object sender, EventArgs e)
        {
            try
            {
                d_soluong = (soluong.Text != "") ? decimal.Parse(soluong.Text) : 0;
                soluong.Text = d_soluong.ToString("###,###,###,##0.00");
                if (d_soluong == 0 && soluong.Enabled)
                {
                    MessageBox.Show("Nhập số lượng !");
                    soluong.Focus();
                }
                if (d_soluong < 0 && soluong.Enabled)
                {
                    MessageBox.Show("Số lượng không hợp lệ !");
                    soluong.Focus();
                }
                if (mathuoc.Text != "" && tenthuoc.Text != "")
                {
                    DataRow r = m.getrowbyid(dtmabd, "ma='" + mathuoc.Text + "'");
                    if (r != null)
                    {
                        i_mabd = int.Parse(r["id"].ToString());
                        decimal d_soluongton = m.get_slton_nguon(dtmabd, i_makho, i_mabd, i_manguon, d_soluongcu);
                        if (d_soluong > d_soluongton)
                        {
                            MessageBox.Show("Số lượng xuất lớn hơn số lượng tồn !(" + d_soluongton.ToString() + ")", DAL.AccessData.Msg);
                            soluong.Focus();
                            return;
                        }
                    }
                }
            }
            catch { }
        }
        private void butXoa_Click(object sender, EventArgs e)
        {
            if (mathuoc.Text == "" || tenthuoc.Text == "" || i_mabd == 0) return;
            DataRow r = m.getrowbyid(dtct, "mabd=" + i_mabd);
            if (r != null)
            {
                if (bEdit) m.updrec_donthuocct(dtxoa, long.Parse(r["id"].ToString()), int.Parse(r["stt"].ToString()), i_mabd, r["ma"].ToString(), r["ten"].ToString(), r["tenhc"].ToString(), r["dang"].ToString(), decimal.Parse(r["soluong"].ToString()), r["cachdung"].ToString(), int.Parse(r["makho"].ToString()), int.Parse(r["manguon"].ToString()),dtmabd);
                m.delrec(dtct, "mabd=" + i_mabd + " and stt=" + int.Parse(r["stt"].ToString()));
                dtct.AcceptChanges();
                dataGrid1.Refresh();
            }
            if (dtct.Rows.Count == 0) emp_detail();
            else ref_text();
        }

        private void dataGrid1_CurrentCellChanged(object sender, EventArgs e)
        {
            ref_text();
            if(!bNew && !bEdit) ena_object(false);
        }
        private void ena_object(bool ena)
        {
            mathuoc.Enabled=ena;
            tenthuoc.Enabled = ena;
            soluong.Enabled = ena;
            cachdung.Enabled = ena;
            ghichu.Enabled = ena;
        }
        private void ref_text()
        {
            try
            {
                int i = dataGrid1.CurrentCell.RowNumber;
                i_stt = int.Parse(dataGrid1[i, 1].ToString());
                i_mabd = int.Parse(dataGrid1[i, 2].ToString());
                mathuoc.Text = dataGrid1[i, 3].ToString();
                tenthuoc.Text = dataGrid1[i, 4].ToString();
                hoatchat.Text = dataGrid1[i, 5].ToString();
                dvt.Text = dataGrid1[i, 7].ToString();
                d_soluong = decimal.Parse(dataGrid1[i, 6].ToString());
                soluong.Text = d_soluong.ToString("###,###,###,##0.00");
                cachdung.Text = dataGrid1[i, 8].ToString();
                i_makho = int.Parse(dataGrid1[i, 9].ToString());
                i_manguon = int.Parse(dataGrid1[i, 10].ToString());
                d_soluongcu = (bNew) ? 0 : d_soluong;
            }
            catch { }
        }

        private void mathuoc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up) listthuoc.Focus();
            else if (e.KeyCode == Keys.Enter)
            {
                if (listthuoc.Visible) listthuoc.Focus();
                else SendKeys.Send("{Tab}{Home}");
            }
        }

        private void mathuoc_TextChanged(object sender, EventArgs e)
        {
            if (this.ActiveControl == mathuoc)
            {
                try
                {
                    Filt_tenthuoc(mathuoc.Text);
                    //listthuoc.BrowseToTonkho(tenthuoc, mathuoc, soluong, mathuoc.Location.X, mathuoc.Location.Y + mathuoc.Height, mathuoc.Width + tenthuoc.Width + lTenthuoc.Width - 4, mathuoc.Height);
                    listthuoc.Tonkhoct(tenthuoc, mathuoc, soluong, mathuoc.Location.X, mathuoc.Location.Y + mathuoc.Height, mathuoc.Width + tenthuoc.Width + lTenthuoc.Width - 4, mathuoc.Height);
                }
                catch { }
            }
        }

        private void cachdung_Validated(object sender, EventArgs e)
        {
            if (!listcachdung.Focused) listcachdung.Hide();
        }

        private void tenthuoc_Validated(object sender, EventArgs e)
        {
            if (!listthuoc.Focused) listthuoc.Hide();
        }

        private void listcachdung_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    DataRow r = m.getrowbyid(dtcachdung, "id=" + macachdung.Text.Trim());
                    if (r == null)
                    {
                        macachdung.Text = "";
                    }
                }
                catch { macachdung.Text = ""; }
            }
        }
    }
}